package com.xlongwei.logserver;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.io.input.Tailer;
import org.apache.commons.io.input.TailerListener;
import org.apache.commons.io.input.TailerListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.networknt.utility.StringUtils;

public class FileBeat {
	public static Logger log = LoggerFactory.getLogger("filebeat");
	public static List<Tailer> tailers = new LinkedList<>();
	public static TailerListener listener = new TailerListenerAdapter() {
		@Override
		public void handle(String line) {
			if (StringUtils.isBlank(line)) {
				return;
			} else if (line.contains(" WARN ")) {
				log.warn(line);
			} else if (line.contains(" ERROR ")) {
				log.error(line);
			} else {
				log.info(line);
			}
		}
	};

	public static void main(String[] args) {
		String filebeat = System.getProperty("filebeat");
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String now = df.format(new Date());
		log.info("filebeat {} INFO files: {}", now, filebeat);
		if (StringUtils.isNotBlank(filebeat)) {
			filebeat(filebeat);
			Runtime.getRuntime().addShutdownHook(new Thread() {
				@Override
				public void run() {
					tailers.forEach(tailer -> tailer.stop());
				}
			});
		}
	}

	public static void filebeat(String filebeat) {
		if (StringUtils.isBlank(filebeat)) {
			return;
		}
		for (String filepath : filebeat.split("[,;]")) {
			File file = new File(filepath);
			log.warn("tailer file: {}", filepath);
			Tailer tailer = Tailer.create(file, StandardCharsets.UTF_8, listener, 1000, true, false, 4096);
			tailers.add(tailer);
		}
	}
}
